package com.atgm.mall.gmmallauth.service.impl;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atgm.common.exception.BizCodeEnume;
import com.atgm.common.exception.MemberException;
import com.atgm.common.utils.HttpClientUtils;
import com.atgm.common.utils.R;
import com.atgm.common.vo.login.WeiboUser;
import com.atgm.mall.gmmallauth.feign.MemberFeignService;
import com.atgm.mall.gmmallauth.service.OAuthService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class OAuthServiceImpl implements OAuthService {

    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private Environment environment;

    @Override
    public String handlerWeiboLogin(String code) {
        String memberId = "";
        Map<String, String> map = new HashMap<>();
        map.put("client_id", "477905441");
        map.put("client_secret", "0c9fecdcfc16af03c4bb302940dc65e0");
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", "http://gmmallauth.com/weibo/login");
        map.put("code", code);
        try {
            HttpResponse response = HttpClientUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", null, null, map);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                byte[] bytes = EntityUtils.toByteArray(entity);
                String string = new String(bytes);
                WeiboUser weiboUser = JSON.parseObject(string, WeiboUser.class);
                log.info("weiboUser : {}", weiboUser);
                //调用member服务，处理登录
                R r = memberFeignService.handlerWeiboLogin(weiboUser);
                if (r.getCode() == 0) {
                    memberId = r.getData(new TypeReference<String>() {});
                    log.info("memberEntity : {}", memberId);
                }
            }else {
                throw new MemberException(BizCodeEnume.USER_LOGIN.getMsg(), BizCodeEnume.USER_LOGIN.getCode());
            }
        }catch (Exception e) {
            e.printStackTrace();
            throw new MemberException(BizCodeEnume.USER_LOGIN.getMsg(), BizCodeEnume.USER_LOGIN.getCode());
        }
        return memberId;
    }
}
